package ntancnit.app.whereareyou;

import ntancnit.app.database.GetUserName;
import ntancnit.app.network.Config;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginScreen extends Activity implements OnClickListener{

	private final int HANDLE_ERROR = 0;
	private final int HANDLE_SUCCESS = 1;
	private EditText edName;
	private Button btnLogin;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_sreen);

		edName = (EditText) findViewById(R.id.editText1);
		btnLogin = (Button) findViewById(R.id.button1);
		btnLogin.setOnClickListener(this);
	}

	private Handler myHandler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLE_ERROR:

				break;
			case HANDLE_SUCCESS:
				saveUser();
				goHome();
				break;
			default:
				break;
			}
		}
	};
	
	private void saveUser(){
		GetUserName userName = new GetUserName(LoginScreen.this);
		userName.insertUser(edName.getText().toString());
	}
	
	private void goHome(){
		SharedPreferences prefs = this.getSharedPreferences(
				Config.SHAREDPREFERENCES_DATA, Context.MODE_PRIVATE);
		prefs.edit().putBoolean("isLogedIn", true).commit();
		Intent intent = new Intent(LoginScreen.this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			Message m = new Message();
			m.what = HANDLE_SUCCESS;
			LoginScreen.this.myHandler.sendMessage(m);
			break;
		default:
			break;
		}
	}

}
